package com.stylefeng.guns.modular.netcar.service.impl;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.model.CommonKeyValue;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.PingYinUtil;
import com.stylefeng.guns.modular.netcar.dao.OrderLineMapper;
import com.stylefeng.guns.modular.netcar.model.*;
import com.stylefeng.guns.modular.netcar.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**

 * 订单线路信息 Service 实现
 * @author sasazaixian
 * @Date 2018-10-24 15:01
 */
@Service
public class OrderLineServiceImpl extends ServiceImpl<OrderLineMapper,OrderLine> implements IOrderLineService {

    @Resource
    private OrderLineMapper orderLineMapper;
    @Autowired
    private ILineDatePriceService lineDatePriceService;
    @Autowired
    private ILineMileagePriceService lineMileagePriceService;
    @Autowired
    private ILinePriceService linePriceService;
    @Autowired
    private ILineRangePriceService lineRangePriceService;
    @Autowired
    private ILineTimePriceService lineTimePriceService;
    @Autowired
    private ILineSiteService lineSiteService;
    @Autowired
    private IOrderInfService orderInfService;
    @Autowired
    private ILineDispatchPsnService lineDispatchPsnService;


    private static final String CACHE_STRATEGY = "local";
    /**
     * 删除订单线路信息
     * @param orderLine
     * @return
     */
    @Transactional
    public int deleteOrderLine(OrderLine orderLine,String token)throws Exception{
        if(orderLine==null ){
            throw new RuntimeException("参数不全！");
        }

        List<OrderLine> orderLineList=orderLineMapper.selectListOrderLine(orderLine);
        for(OrderLine en:orderLineList){
            String id=en.getOlId();
            OrderInf orderInf=new OrderInf();
            orderInf.setOlId(id);
            List list= orderInfService.selectListOrderInf(orderInf,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在订单中引用，不能删除！");
            }

            LineDatePrice lineDatePrice=new LineDatePrice();
            lineDatePrice.setOlId(id);
            list= lineDatePriceService.selectListLineDatePrice(lineDatePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineMileagePrice lineMileagePrice=new LineMileagePrice();
            lineMileagePrice.setOlId(id);
            list= lineMileagePriceService.selectListLineMileagePrice(lineMileagePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LinePrice linePrice=new LinePrice();
            linePrice.setOlId(id);
            list= linePriceService.selectListLinePrice(linePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineRangePrice lineRangePrice=new LineRangePrice();
            lineRangePrice.setOlId(id);
            list= lineRangePriceService.selectListLineRangePrice(lineRangePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineTimePrice lineTimePrice=new LineTimePrice();
            lineTimePrice.setOlId(id);
            list= lineTimePriceService.selectListLineTimePrice(lineTimePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineSite lineSite=new LineSite();
            lineSite.setOlId(id);
            list= lineSiteService.selectListLineSite(lineSite,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在站点中引用，不能删除！");
            }

            LineDispatchPsn lineDispatchPsn=new LineDispatchPsn();
            lineDispatchPsn.setOlId(id);
            list= lineDispatchPsnService.selectListLineDispatchPsn(lineDispatchPsn,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经指派了调度员，不能删除！");
            }
        }
        return this.orderLineMapper.deleteOrderLine(orderLine);
    }
    /**
     * 批量删除订单线路信息
     * @param ids 主键ID数组
     * @return
     */
    @Transactional
    public int deleteBatchOrderLine(String[] ids,String token)throws Exception{
        for(String id:ids){
            OrderInf orderInf=new OrderInf();
            orderInf.setOlId(id);
            List list= orderInfService.selectListOrderInf(orderInf,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在订单中引用，不能删除！");
            }

            LineDatePrice lineDatePrice=new LineDatePrice();
            lineDatePrice.setOlId(id);
            list= lineDatePriceService.selectListLineDatePrice(lineDatePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineMileagePrice lineMileagePrice=new LineMileagePrice();
            lineMileagePrice.setOlId(id);
            list= lineMileagePriceService.selectListLineMileagePrice(lineMileagePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LinePrice linePrice=new LinePrice();
            linePrice.setOlId(id);
            list= linePriceService.selectListLinePrice(linePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineRangePrice lineRangePrice=new LineRangePrice();
            lineRangePrice.setOlId(id);
            list= lineRangePriceService.selectListLineRangePrice(lineRangePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineTimePrice lineTimePrice=new LineTimePrice();
            lineTimePrice.setOlId(id);
            list= lineTimePriceService.selectListLineTimePrice(lineTimePrice,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在线路价格中引用，不能删除！");
            }

            LineSite lineSite=new LineSite();
            lineSite.setOlId(id);
            list= lineSiteService.selectListLineSite(lineSite,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经在站点中引用，不能删除！");
            }

            LineDispatchPsn lineDispatchPsn=new LineDispatchPsn();
            lineDispatchPsn.setOlId(id);
            list= lineDispatchPsnService.selectListLineDispatchPsn(lineDispatchPsn,token);
            if(list!=null && list.size()>0){
                throw new RuntimeException("已经指派了调度员，不能删除！");
            }
        }

        return this.orderLineMapper.deleteBatchOrderLine(ids);
    }
    /**
     * 查询订单线路信息列表
     * @param orderLine 订单线路信息对象
     * @return
     */
    public List<OrderLine> selectListOrderLine(OrderLine orderLine,String token)throws Exception{
        if(orderLine!=null && orderLine.getIsApply()!=null && orderLine.getIsApply().trim().equals("1")){
            ShiroUser shiroUser= CacheKit.get(CACHE_STRATEGY, token);
            orderLine.setAppliSoId(shiroUser.soId);
        }
        if(orderLine!=null && orderLine.getDispather()!=null && orderLine.getDispather().equals("1")){
            orderLine.setDispatherLineIds(getDispatherLineIds(token));
        }
        return  this.orderLineMapper.selectListOrderLine(orderLine);
    }

    @Override
    public List<OrderLine> selectListOrderLine(String isAll, String state, String token) throws Exception {

        if(isAll==null || !(isAll.equals("0") || isAll.equals("1")) ){
            throw new RuntimeException("参数不全！");
        }
        OrderLine orderLine =new OrderLine();
        if(state!=null && (state.equals("0") || state.equals("1"))){
            orderLine.setOlIsAlived(state);
        }
        if(isAll.equals("0")){
            orderLine.setDispatherLineIds(getDispatherLineIds(token));
            orderLine.setDispather("1");
        }
        orderLine.setCheckResult("6");
        List<OrderLine> listOrderLine=this.orderLineMapper.selectListOrderLine(orderLine);
        Map<String,List<OrderLine>> mapLine=new TreeMap();
        for(OrderLine lineInf :listOrderLine){
            String olName=lineInf.getOlName();
            lineInf.setPyAll(PingYinUtil.getPinyin(olName));
            String pyHead=PingYinUtil.getPinYinHeadChar(olName);
            String pyFirst=pyHead.substring(0,1);
            lineInf.setPyHead(pyHead);
            lineInf.setPyFirst(pyFirst);
            List<OrderLine> tempList=null;
            if(!mapLine.containsKey(pyFirst)){
                mapLine.put(pyFirst,new ArrayList<OrderLine>());
            }
            tempList=mapLine.get(pyFirst);
            tempList.add(lineInf);
        }
        listOrderLine.clear();
        Iterator<String> it=mapLine.keySet().iterator();
        while(it.hasNext()){
            listOrderLine.addAll(mapLine.get(it.next()));
        }
        //根据拼音首字母排序
        return listOrderLine;
    }

    private String getDispatherLineIds(String token)throws Exception{
        LineDispatchPsn lineDispatchPsn=new LineDispatchPsn();
        String suId=JwtTokenUtil.getClaimFromToken(token).getSubject();
        if(suId==null || suId.trim().length()==0){
            throw new RuntimeException("请登录！");
        }
        lineDispatchPsn.setSuId(suId);
        List<LineDispatchPsn> listDispatchPsn= lineDispatchPsnService.selectListLineDispatchPsn(lineDispatchPsn,token);
        String lineIds="";
        for(LineDispatchPsn en:listDispatchPsn){
            lineIds+=",'"+en.getOlId()+"'";
        }
        if(lineIds.length()>1){
            lineIds=lineIds.substring(1);
        }else{
            lineIds="''";
        }
        return lineIds;
    }
    /**
	 * 分页查询订单线路信息列表
     * @param pager 分页对象
     * @return
     */
    public  Map pageListOrderLine(Pager pager,String token) throws Exception{
        Page page=new Page(pager.getPageNumber(),pager.getPageSize());
        OrderLine orderLine=(OrderLine)pager.getObj();
        if(orderLine.getIsApply()!=null && orderLine.getIsApply().trim().equals("1")){
            ShiroUser shiroUser= CacheKit.get(CACHE_STRATEGY, token);
            orderLine.setAppliSoId(shiroUser.soId);
        }
        if(orderLine!=null && orderLine.getDispather()!=null && orderLine.getDispather().equals("1")){
            orderLine.setDispatherLineIds(getDispatherLineIds(token));
        }
        page.setRecords(orderLineMapper.selectListOrderLine(page,orderLine));

        List<OrderLine> list = page.getRecords();
        Map mapDate = new HashMap();
        mapDate.put("rows", list);
        mapDate.put("total", page.getTotal());
        mapDate.put("page", page.getCurrent());
        mapDate.put("pageCount", page.getPages());
        return mapDate;
    }
    /**
     * 同一个事务 互斥锁查询
     * @param orderLine 订单线路信息对象
     * @return
     */
    public  List<OrderLine> selectListOrderLineForUpdate(OrderLine orderLine)throws Exception{
        return  this.orderLineMapper.selectListOrderLineForUpdate(orderLine);
    }
    /**
     * 通过主键id查询的订单线路信息列表
     * @param id 主键id
     * @return
     */
    public  OrderLine findOrderLineById(String id,String token)throws Exception{
        return  this.orderLineMapper.findOrderLineById(id);
    }
    /**申请线路机构只可以看到自己的  申请线路必须填写包含价格信息 接送区域 不包含排班
       审批可以看到所有申请的线路
       对于以上两种分别做查询
    */
     /**
     * 新增订单线路信息数据
     * @param orderLine 订单线路信息对象
     * @return
     */
    @Transactional
    public int insertOrderLine(OrderLine orderLine,String token) throws Exception {
        if(orderLine!=null && (orderLine.getOlId()==null || orderLine.getOlId().trim().length()<10)){
            orderLine.setOlId(IdWorker.get32UUID());
        }
        ShiroUser shiroUser= CacheKit.get(CACHE_STRATEGY, token);
        if(shiroUser!=null)
            orderLine.setAppliSoId(shiroUser.soId);
        else
            throw new GunsException(BizExceptionEnum.TOKEN_EXPIRED);

        if(orderLine.getCheckResult()==null){//0：起草中，1：审批中，2：退回 6：审批通过
            orderLine.setCheckResult("0");
        }
        return this.orderLineMapper.insertOrderLine(orderLine);
    }
    
    /**
     * 更新订单线路信息数据
     * @param orderLine 订单线路信息对象
     * @return
     */
    @Transactional
    public int updateOrderLine(OrderLine orderLine,String token) throws Exception {
        orderLine.setAppliSoId(null);//不能修改线路申请的所属机构
        return  this.orderLineMapper.updateOrderLine(orderLine);
    }
    /**
     * 查询订单线路信息返回key-Value属性
     * @param orderLine 系统操作对象
     * @return
     */
    public List<CommonKeyValue> optionsOrderLine(OrderLine orderLine,String token) throws Exception {
        List<OrderLine> listOrderLine=this.orderLineMapper.selectListOrderLine(orderLine);
        List<CommonKeyValue> listOptions=new ArrayList<CommonKeyValue>();
        for(OrderLine item:listOrderLine){
            CommonKeyValue opts=new CommonKeyValue();
            opts.setId(""+item.getOlId());
            opts.setValue(item.getOlName());
            listOptions.add(opts);
        }
        return listOptions;
    }
}
